const Service = require("egg").Service;

class UserService extends Service {


  async list({ offset = 0, limit = 10 }) {
    return this.ctx.model.Syuser.findAndCountAll({
      offset,
      limit,
      attributes: [ 'userid', 'username', 'Co_ID', 'created_at', 'updated_at' ],
      order: [[ 'created_at', 'desc' ], [ 'userid', 'desc' ]],
    });
  }


  async create(user) {
    return this.ctx.model.Syuser.create(user);
  }

  async destroy(userid) {
    const user = await this.ctx.model.Syuser.findByPk(userid)
    return await user.destroy();
  }


  async update(userid, payload) {

    const user = await this.ctx.model.Syuser.findByPk(userid)
    if (!user) {
      this.ctx.throw(422, ctx.__('user not found'));
    }
    await user.update(payload);
    return user;
  }


  async show(userid) {

    const user = await this.ctx.model.Syuser.findByPk(userid)
    if (!user) {
      this.ctx.throw(422, ctx.__('user not found'));
    }
    return user;
  }

  async removes(where) {
    await this.ctx.model.Syuser.destroy({
      where
    });
  }


  async findByUsername(name, options={}) {
    const where = { where: { username: name }, ...options }
    return await this.ctx.model.Syuser.findOne(where);
  }

  async find(...args) {
    return await this.ctx.model.Syuser.findOne({ ...args });
  }

}

module.exports = UserService;
